package com.wh.wisdomsite.xbox.server.controller.st;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.wh.wisdomsite.xbox.common.Constants;
import com.wh.wisdomsite.xbox.common.reponse.CommonResult;
import com.wh.wisdomsite.xbox.common.util.ResManager;
import com.wh.wisdomsite.xbox.core.XboxException;
import com.wh.wisdomsite.xbox.server.util.UserUtils;
import com.wh.wisdomsite.xbox.st.entity.Material;
import com.wh.wisdomsite.xbox.st.entity.PurchaseApply;
import com.wh.wisdomsite.xbox.st.entity.PurchaseDetail;
import com.wh.wisdomsite.xbox.st.service.IPurchaseApplyService;
import com.wh.wisdomsite.xbox.st.service.IPurchaseDetailService;
import com.wh.wisdomsite.xbox.us.entity.User;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/***
 *采购清单Controller
 * @author 杨世强
 * @date 16:40 2018/8/2
 * @Copyright 公司版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2016
 * @version V1.0
 */
@Controller
@RequestMapping(value = "/purchaseDetail")
public class PurchaseDetailController {

    private static final Log logger = LogFactory.getLog(PurchaseDetailController.class);

    @Autowired
    private IPurchaseDetailService ipurchaseDetailService;

    @Autowired
    private IPurchaseApplyService iPurchaseApplyService;

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 跳转到采购清单编辑页面
     * @return
     */
    @RequestMapping(value = "/toPurchaseDetailEdit.do", method = RequestMethod.GET)
    public String toPurchaseDetailEdit(String purId, HttpServletRequest request){
        try{
            logger.info("添加采购申请跳转-->>开始");
            //注入请购申请信息
            EntityWrapper<PurchaseApply> ew = new EntityWrapper<>();
            ew.setEntity(new PurchaseApply());
            ew.eq("pur.purId", purId);
            PurchaseApply purchaseApply = iPurchaseApplyService.selectOne(ew);
            request.setAttribute("purchaseApply", purchaseApply);
            request.setAttribute("purchaseDate", simpleDateFormat.format(purchaseApply.getPurDate()));
            //注入此请购申请的清单列表信息
            EntityWrapper<PurchaseDetail> purDelEw = new EntityWrapper<>();
            purDelEw.setEntity(new PurchaseDetail());
            purDelEw.eq("pur.purId", purId);

            List<Map<String, Object>> purchaseDetailList = ipurchaseDetailService.getPurchaseDetailMaps(purDelEw);
            request.setAttribute("purchaseDetailList", JsonUtil.Json2All(purchaseDetailList));
            logger.info("添加采购申请跳转-->>结束");
        }catch (Exception e){
            e.printStackTrace();
            logger.error("添加采购申请跳转-->>Exception" + e.getMessage());
        }
        return "/st/purchaseApply/purchaseDetailEdit";
    }

    /**
     * 保存采购清单
     * @param purchaseApply
     * @param request
     * @param response
     */
    @RequiresPermissions("rules:st_purchaseDetail_edit")
    @RequestMapping(value = "/save.do", method = RequestMethod.POST)
    public void save(PurchaseApply purchaseApply, HttpServletRequest request, HttpServletResponse response){
        logger.info("保存采购清单-->>开始");
        CommonResult commonResult = new CommonResult();
        try{
            if(StringUtils.isEmpty(purchaseApply.getPurId())){
                commonResult.setCode(Constants.CODE_FAIL);
                commonResult.setMessage("发生错误，请购ID不能为空");
                ResManager.getTextOut(response).print(JsonUtil.Json2All(commonResult));
                return;
            }
            if(StringUtils.isEmpty(purchaseApply.getPurType())){
                commonResult.setCode(Constants.CODE_FAIL);
                commonResult.setMessage("发生错误，请购类型不能为空");
                ResManager.getTextOut(response).print(JsonUtil.Json2All(commonResult));
                return;
            }
            //用于在service中存储的清单List
            List<PurchaseDetail> detailList = new ArrayList<>();
            //当前操作用户
            User curUser = UserUtils.getCurrentUser();

            String[] purdIds = request.getParameterValues("purdId");
            String[] materialNames = request.getParameterValues("materialName");
            String[] brand = request.getParameterValues("brand");
            String[] technicalParameter = request.getParameterValues("technicalParameter");
            String[] standardTypes = request.getParameterValues("standardType");
            String[] meteringUnits = request.getParameterValues("meteringUnit");
            String[] unitPrices = request.getParameterValues("unitPrice");
            String[] purdNums = request.getParameterValues("purdNum");
            /*String[] characterizations = request.getParameterValues("characterization");
            String[] explains = request.getParameterValues("explain");
            String[] belongSystems = request.getParameterValues("belongSystem");*/
            String[] reqRemarks = request.getParameterValues("reqRemark");


            //遍历前端传入的所有行
            for(int index = 0; index < purdIds.length; index ++ ){
                //验证数据是否正确
                if(StringUtils.isEmpty(materialNames[index])){
                    commonResult.setCode(Constants.CODE_FAIL);
                    commonResult.setMessage("发生错误，第"+index+"行数据物料名称为空");
                    ResManager.getTextOut(response).print(JsonUtil.Json2All(commonResult));
                    return;
                }
                if(StringUtils.isEmpty(standardTypes[index])){
                    commonResult.setCode(Constants.CODE_FAIL);
                    commonResult.setMessage("发生错误，第"+index+"行数据规格型号为空");
                    ResManager.getTextOut(response).print(JsonUtil.Json2All(commonResult));
                    return;
                }
                if(StringUtils.isEmpty(unitPrices[index])){
                    commonResult.setCode(Constants.CODE_FAIL);
                    commonResult.setMessage("发生错误，第"+index+"行数据采购单价为空");
                    ResManager.getTextOut(response).print(JsonUtil.Json2All(commonResult));
                    return;
                }
                if(StringUtils.isEmpty(purdNums[index])){
                    commonResult.setCode(Constants.CODE_FAIL);
                    commonResult.setMessage("发生错误，第"+index+"行数据请购数量为空");
                    ResManager.getTextOut(response).print(JsonUtil.Json2All(commonResult));
                    return;
                }
                //根据一行录入的数据，创建物料
                Material material = new Material();
                material.setMaterialName(materialNames[index]);
                material.setStandardType(standardTypes[index]);
                material.setMeteringUnit(meteringUnits[index]);
                material.setUnitPrice(Double.valueOf(unitPrices[index]));
                material.setBrand(brand[index]);
                material.setTechnicalParameter(technicalParameter[index]);
               /* material.setCharacterization(characterizations[index]);*/

                //创建需要向清单List中添加的请购清单
                PurchaseDetail purchaseDetail = new PurchaseDetail();
                purchaseDetail.setMaterial(material);
                purchaseDetail.setPurdId(purdIds[index]);
                purchaseDetail.setPurdNum(Double.valueOf(purdNums[index]));
                purchaseDetail.setPurdTotalPrice(purchaseDetail.getPurdNum() * material.getUnitPrice());
                /*purchaseDetail.setExplain(explains[index]);
                purchaseDetail.setBelongSystem(belongSystems[index]);*/
                purchaseDetail.setReqRemark(reqRemarks[index]);
                detailList.add(purchaseDetail);
            }
            commonResult = ipurchaseDetailService.saveOrUpdate(purchaseApply ,detailList, curUser);
            ResManager.getTextOut(response).print(JsonUtil.Json2All(commonResult));
            logger.info("保存采购清单-->>结束");
        }catch (XboxException xe){
            commonResult.setCode(Constants.CODE_FAIL);
            commonResult.setMessage(xe.getMessage());
            ResManager.getTextOut(response).print(JsonUtil.Json2All(commonResult));
            xe.printStackTrace();
            logger.debug("保存采购清单-->>Exception" + xe.getMessage());
        }catch (Exception e) {
            commonResult.setCode(Constants.CODE_FAIL);
            commonResult.setMessage("发生未知错误，请联系系统管理员解决");
            ResManager.getTextOut(response).print(JsonUtil.Json2All(commonResult));
            e.printStackTrace();
            logger.error("保存采购清单-->>Exception" + e.getMessage());
        }
    }

    /**
     * 删除采购清单
     * @param
     * @param response
     */
    @RequiresPermissions("rules:st_purchaseDetail_del")
    @RequestMapping(value = "/del.do", method = RequestMethod.GET)
    public void del(String purdId, HttpServletResponse response) {
        CommonResult commonResult = new CommonResult();
        try {
            logger.info("删除采购清单-->>开始");
            ipurchaseDetailService.deleteById(purdId);
            logger.info("删除采购清单-->>结束");
            commonResult.setCode(Constants.CODE_SUCCESS);
            commonResult.setMessage("删除成功");
            ResManager.getTextOut(response).print(JsonUtil.Json2All(commonResult));
        } catch (Exception e) {
            e.printStackTrace();
            commonResult.setCode(Constants.CODE_FAIL);
            commonResult.setMessage("因发生未知错误删除失败，请联系管理员解决");
            ResManager.getTextOut(response).print(JsonUtil.Json2All(commonResult));
            logger.error("删除采购清单-->>Exception" + e.getMessage());
        }
    }
}
